package me.zk.practice1.thread;

import java.util.concurrent.TimeUnit;

/**
 * 验证volatile
 * @Author: zhang kai
 * @Date: 2021/12/18
 * @Description:
 */
public class Demo {
    volatile int i = 0;
    public synchronized void addI() {
        i++;
    }
    public static void main(String[] args) {
       Demo demo = new Demo();
       for (int i =0; i < 20; i++){
           new Thread(() -> {
               for (int j = 0; j < 1000; j++) {
                   demo.addI();
               }
           }).start();
       }
       //判断是否还有其他线程在运行
       //后台默认两个线程主线程和GC线程
       while (Thread.activeCount() > 2) {
           Thread.yield();
       }
        System.out.println(demo.i);
    //    checkVolatile();
    }
    public static void checkVolatile() {
        Demo demo = new Demo();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println("update i = 60");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            demo.i = 60;}).start();

        //主线程
        while (demo.i == 0) {

        }
    }

}
